package com.example.ktdemo.selection;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.animation.LinearInterpolator;

import androidx.constraintlayout.widget.ConstraintLayout;


/**
 * FileName: SelectionRootView
 * Author: lzt
 * Date: 2022/10/9 19:12
 * 选项必须继承该类实现
 */
public class SelectionRootView extends ConstraintLayout {
    //透明度时长
    private static final long TIME_ANIM_ALPHA_DURATION = 300;

    private ShowHideEventListener mListener;

    public SelectionRootView(Context context) {
        super(context);
    }

    public SelectionRootView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SelectionRootView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        clearAnimation();
        setAlpha(1);
    }

    @Override
    protected void onDetachedFromWindow() {
        clearAnimation();
        super.onDetachedFromWindow();

    }

    /**
     * 隐藏
     */
    public void hide() {
        setAlpha(0);
    }

    /**
     * 显示
     */
    public void show() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, 1f);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.setDuration(TIME_ANIM_ALPHA_DURATION);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float cacheValue = (float) animation.getAnimatedValue();
                setAlpha(cacheValue);
            }
        });
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (mListener != null) {
                    mListener.entireShow();
                }
            }
        });
        valueAnimator.start();
        if (mListener != null) {
            mListener.startShow();
        }
    }

    //监听事件
    public void setShowHideEventListener(ShowHideEventListener listener) {
        this.mListener = listener;
    }

    public void removeShowHideEventListener() {
        this.mListener = null;
    }

    public interface ShowHideEventListener {

        /**
         * 完全显示
         */
        void entireShow();

        /**
         * 开始显示
         */
        void startShow();
    }

}
